<?php
	require_once($GLOBALS['BIB']."Objects/obj.mail.mex");

	//=============== Caixa Populate ================
	$qr_OBJ = 0;
	$Fi1 = $sysTime;
	$Fi2 = $_SESSION[$SESSID];
	$Fi3 = $_SESSION[$SESSCD];
	$m = 1;
	$t = 0;
	$ORPool = substr($_POST['POOL'],0,strlen($_POST['POOL'])-1);
	$MailPool = preg_split('/,/',$ORPool);
	sort($MailPool);
	$MailCard = $_POST['SumCard']-1;
	$PrcResult = 0;
	// File
	$File = $_SESSION[$SESSCD].DATE("YmdHis").'OTRNS.xls';


	if($_POST['TRANSTYPE'] == 1) {
		$rp_dep = 8;
		if($_POST['View'] == 1) {
			$Fi4 = 0;
			$Fi5 = $_POST['TRANSVIEW'];
			$Fi6 = 0;
			$Fi7 = 1;
		} elseif($_POST['View'] == 2) {
			$Fi4 = $_POST['TRANSVIEW'];
			$Fi5 = 0;
			$Fi6 = 0;
			$Fi7 = 1;
		} elseif($_POST['View'] == 3) {
			$Fi4 = 0;
			$Fi5 = 0;
			$Fi6 = $_POST['TRANSVIEW'];
			$Fi7 = 1;
		}
	} else {
		$rp_dep = 9;

			$Fi4 = 0;
			$Fi5 = 0;
			$Fi6 = 0;
			$Fi7 = $_POST['TRANSVIEW'];
	}
	# CONN PROCEDURE # DO DOMAIN TRANSMITION
	CONN('MYI');
	$GLOBALS['MYI']->multi_query("CALL do_domaintrans({$_POST['TRANSTYPE']},{$Fi3},{$Fi2},{$Fi4},{$Fi5},{$Fi6},{$Fi7},
			'{$ORPool}','{$Fi1}','{$_POST['TTime']}','{$_POST['sysMailTopic']}','{$File}',{$_POST['SumEnviado']},{$_POST['SumValues']},
			'".$MailPool[0]." ".$MailPool[$MailCard]."', @ConfResult); SELECT @ConfResult");
	 do {
        if ($result = $GLOBALS['MYI']->store_result()) {
            while ($row = $result->fetch_row()) {
			$PrcResult = $row[0];
            }
            $result->free();
        }
    } while ($GLOBALS['MYI']->next_result());
	$GETACCOUNT = $GLOBALS['MYT']->db_array("SELECT ctoID FROM cuentasagentes WHERE ctoAgente = {$_SESSION[$SESSID]}");
	if(isset($GETACCOUNT[1])){
	$GLOBALS['MYI']->multi_query("CALL fn_accountmoviment({$GETACCOUNT[1]['ctoID']},0,2,'{$sysTime}','{$_POST['TTime']}',{$_SESSION[$SESSID]},{$_POST['SumEnviado']}, @prResult); SELECT @prResult");
	 do {
        if ($result = $GLOBALS['MYI']->store_result()) {
            while ($row = $result->fetch_row()) {
			$MovResult = $row[0];
            }
            $result->free();
        }
    } while ($GLOBALS['MYI']->next_result());

	}
	$GLOBALS['MYI']->close();
	if ($PrcResult > 0 && $_POST['TRANSTYPE'] == 1){
		// MakeFile
		require_once($GLOBALS['BIB']."/FileTemplates/SpreadSheets/tReport01.mex");
		$CONTENTS = "SELECT FraID AS Field1, CONCAT(FraOrigen0,'-',LPAD(FraReferenciaAg,6,0)) AS Field2, FraTasa AS Field3, FraCargo AS Field4, FraEnviado AS Field5, FraARecibir AS Field6, FraFechaIngreso AS Field7, FraProm AS Field10, CliNombre AS Field8, BnfNombre AS Field9
		FROM Facturas IGNORE INDEX (IdxCli)
		INNER JOIN clientes ON CliNumero = FraCliNumero
		INNER JOIN beneficiarios ON BnfNumero = FraBnfNumero
			WHERE FraID IN ($ORPool) AND FraStatus = 2 AND FraUsuarioAlb = {$Fi2}";
		$SheetPad = $GLOBALS['DOC'].'OFTRANSM/';
		SpreadSheet($SheetPad.$File,$CONTENTS);
		### mudar forma de calculo dos valores, puxar dados do pais e correspondente e caixa
		$GETMAddress = $GLOBALS['MYT']->db_array("SELECT OriNombre, smb_CttEmail, ref, CorrNombre, pai_NombreUSD, cvt_Name FROM systemoffice.main_users
				INNER JOIN systemoffice.staff_members ON smb_ID = StaffMember
				INNER JOIN origenes ON OriNumero = {$_SESSION[$SESSCD]}
				LEFT OUTER JOIN corresponsales ON CorrNumero = {$Fi4}
				LEFT OUTER JOIN hd_paises ON pai_CodElite = {$Fi5}
				LEFT OUTER JOIN hd_cashiertypes ON cvt_ID = {$Fi6}
				LEFT OUTER JOIN hd_monedasiso ON miso_cod_elite = {$Fi7}
				WHERE ref = {$_SESSION[$SESSID]} OR RefDept = {$rp_dep}");
		if($_POST['TRANSTYPE'] == 1){
		$_sysMailTopic = "REMESSAS | {$GETMAddress[1]['OriNombre']} - {$_SESSION[$SESSCD]}, enviado por {$_SESSION[$SESSUS]}";
		} elseif($_POST['TRANSTYPE'] == 2) {
		$_sysMailTopic = "EXCHANGE | {$GETMAddress[1]['OriNombre']} - {$_SESSION[$SESSCD]}, enviado por {$_SESSION[$SESSUS]}";
		}

		$HTML = $_POST['sysMailTopic']."<br />
		----------------------------------------------------------------------------------------<br />";
		if($_POST['TRANSTYPE'] == 1){
			if ($_POST['View'] == 2) {
			$HTML .= "Correspondente: {$GETMAddress[1]['CorrNombre']}";
			} elseif($_POST['View'] == 1) {
			$HTML .= "País: {$GETMAddress[1]['pai_NombreUSD']}";
			} elseif($_POST['View'] == 3) {
			$HTML .= "Caixa: {$GETMAddress[1]['cvt_Name']}";
			}
		} elseif($_POST['TRANSTYPE'] == 2) {
			$HTML .= "Moeda: {$GETMAddress[1]['CorrNombre']}";
		}
		$HTML .= "<br />Valor Total em Euros: {$_POST['SumEnviado']}<br />
		Valor Total no Destino: {$_POST['SumValues']}<br />
		Total de Operações: {$_POST['SumCard']}<br />
		Primeira e última remessa: {$MailPool[0]}, {$MailPool[$MailCard]}<br />
		Data dos valores: {$_POST['TTime']}<br />
		Data do Envio: {$sysTime}";

		$_sysSenderName = $_SESSION[$SESSUS];
		$ATTCH = $SheetPad.$File;
		if (file_exists($ATTCH)) {
			for($r=1;$r<=$GETMAddress[0];$r++) {
			#authmail("<$_sysconfMailName1>",'ASD',$GETMAddress[$r]['smb_CttEmail'],'Lote Loja - '.$_sysSenderName,$_sysMailTopic,'',$HTML,$ATTCH,$_sysconfMailString);
			}

			} elseif($_POST['TRANSTYPE'] == 1) {
			$PrcResult == 0;
		}
	}
	if ($PrcResult == 0){
		echo '<div class="Error">Transmiss&otilde;es - Nao foi possivel transmitir.</div>';
	} else {
	    echo '<div class="Confirm">Transmiss&otilde;es - Operação Executada</div>';

	}
	echo '<script charset="utf-8" type="text/javascript">replaceUrl(\'Subcontents\',\'Modules/DF75HKL0/rs_transmit.mex?TRANSTYPE='.$_POST['TRANSTYPE'].'\');</script>';